package com.ruoyi.central.publisher.subscription.art.process.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.central.domain.TopCentralArtProcess;
import com.ruoyi.central.domain.TopCentralArtProcessRun;
import com.ruoyi.central.publisher.event.ArtProcessEvent;
import com.ruoyi.central.service.ITopCentralArtProcessRunService;
import com.ruoyi.common.enums.common.State;
import com.ruoyi.common.exception.base.service.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Classname ArtProcessEventSubscription
 * @Author: sunluquan
 * @Date: 2022/5/19 09:36
 * @Description TODO
 * 工艺事件对象相关订阅
 */
@Component
@Order(1)
public class ArtProcessEventSubscription {

    @Autowired
    private ITopCentralArtProcessRunService artProcessRunService;
    /**
     * 修改事件订阅
     * @param event
     */
    @EventListener(value = ArtProcessEvent.class,condition = "#event.getSignEnum().name()=='UPDATE'")
    public void updateEvent(ArtProcessEvent event){

        if(getArtProcessRunBindingCount(event,artProcess -> artProcess.getState() == State.DISABLE )>0){
            throw new ServiceException("有正在使用中的工艺，不能修改数据状态为：{}，请先删除 工艺执行数据 ！", State.DISABLE.getInfo());
        }

    }

    /**
     * 查询有多少个执行工艺对象绑定当前需要修改的工艺数据
     * @param event
     * @param predicate 过滤表达式
     * @return
     */
    private long getArtProcessRunBindingCount(ArtProcessEvent event, Predicate<? super TopCentralArtProcess> predicate){
        Collection<TopCentralArtProcess> artProcesses = event.getSources();

        List<Integer> artProcessIds = CollectionUtils.mapToList(artProcesses,TopCentralArtProcess::getId,predicate);

        if(StringUtils.isNotEmpty(artProcessIds)){
            //这个需要获取不需要 对state进行条件过滤的
            LambdaQueryWrapper<TopCentralArtProcessRun> lambdaQuery = artProcessRunService.lambdaQuery();
            if(artProcessIds.size()==1){
                lambdaQuery.eq(TopCentralArtProcessRun::getId, CollectionUtils.getFirst(artProcessIds));
            }else{
                lambdaQuery.in(TopCentralArtProcessRun::getId,artProcessIds);
            }

            return artProcessRunService.getBaseMapper().selectCount(lambdaQuery);

        }
        return Long.MIN_VALUE;
    }

    /**
     * 删除事件订阅
     * @param event
     */
    @EventListener(value = ArtProcessEvent.class,condition = "#event.getSignEnum().name()=='DELETE'")
    public void deleteEvent(ArtProcessEvent event){

        if(getArtProcessRunBindingCount(event,null)>0){
            throw new ServiceException("有正在使用中的工艺，不能进行删除，请先删除 工艺执行数据 ！");
        }

    }


}
